<template>
	<view class="mainBox">
		<view v-if="isAdd">
			<!-- 合同录入 -->
			<view class="tabs page-padding">
				<uni-segmented-control :current="current" :values="tabList" style-type="button" active-color="#007aff"
					@clickItem="onClickTabItem" />
			</view>
			<!-- 合同信息录入 -->
			<baseform v-show="current === 0" ref="form" :groupList='groupList' :pageFormData="pageFormData"
				:formItemList='formItemList' :btnWidth='45' :btnType='"success"' :btnText='"保存"'
				@remoteSearch='remoteSearch' @selectInputChange='selectInputChange' @selectChange='selectChange'
				@submit='saveFunc'>
				<template slot="footButton">
					<u-button type="primary" style="width: 45%;" @click="submit" text="提交"></u-button>
				</template>
			</baseform>
			<!-- 明细信息录入 -->
			<baseform v-show="current === 1" ref="formDetail" :groupList='groupDetailList' :btnText="'新增明细'"
				:pageFormData="pageFormDetailData" :formItemList='formItemDetailList' @remoteSearch='remoteDetailSearch'
				@selectInputChange='selectInputDetailChange' @selectChange='selectDetailChange' @submit='addDetail'>
				<template slot="footSolt">
					<baseTable ref="baseTable" :tableConfig='tableConfig' :tableData='tableData' :rowAlign='"center"'>
					</baseTable>
					<!-- @selectionChange='selectionChange' -->
				</template>
			</baseform>
			<!-- <richEditVue></richEditVue> -->
		</view>
		<view v-else>
			<baseTable ref="contractTable" :tableConfig='contractTableConfig' :tableData='tcontractTableData'
				:rowAlign='"center"' :pageSize='10' @selectionChange='selectionChange' @getRow='getRow'>
				<template slot="footSolt">
					<view class="btn-box">
						<u-button type="primary" @click="add" text="新增"></u-button>
						<u-button type="success" :disabled="!rowIndex" @click="edit" text="编辑"></u-button>
						<u-button type="error" :disabled="!rowIndex" @click="edit" text="删除"></u-button>
					</view>
				</template>
			</baseTable>
		</view>
	</view>
</template>

<script>
	import richEditVue from '@/components/rich-edit/rich-edit.vue'
	import baseform from '@/components/base-form-uni.vue'
	import baseTable from '@/components/base-table.vue'
	export default {
		components: {
			richEditVue,
			baseform,
			baseTable
		},
		data() {
			return {
				rowIndex : undefined,
				rowData: {},
				isAdd: false, // 是否新增
				contractId: '', // 合同ID
				businessType: '', // 业务type
				current: 0, // 标签页索引
				tabList: ['合同信息', '合同明细'],
				sellDepartmentList: [], // 销售部门集合
				customerList: [], // 客户集合
				salespersonList: [], // 销售员集合
				projectList: [], // 项目集合
				kingBankAccountList: [], // 收款账户集合
				materialList: [], // 物料集合
				pageFormData: {}, // 页面表单数据
				pageFormDetailData: {}, // 页面表单明细数据
				formItemList: [], // 页面表单元素配置项集合
				formItemDetailList: [], // 页面表单明细元素配置项集合
				tableConfig: [{
						title: '物料名称',
						key: 'materialName',
						width: '150',
						sortable: false
					},
					{
						title: '物料编号',
						key: 'materialCode',
						width: '',
						sortable: true
					},
					{
						title: '规格型号',
						key: 'model',
						width: '',
						sortable: false
					},
					{
						title: '销售单位',
						key: 'purchaseUnit',
						width: '',
						sortable: false
					},
					{
						title: '销售数量',
						key: 'number',
						width: '',
						sortable: false
					},
					{
						title: '含税单价',
						key: 'detailTaxPrice',
						width: '',
						sortable: false
					},
					{
						title: '价税合计',
						key: 'detailTotalTaxPrice',
						width: '',
						sortable: false
					},
					{
						title: '操作',
						key: 'operation',
						width: '',
						sortable: false,
						isHide: true
					},
				],
				tableData: [],
				contractTableConfig: [{
						title: '序号',
						key: 'rowNo',
						width: '50'
					},
					{
						title: '税额',
						key: 'taxAmount',
						width: '150',
						sortable: false
					},
					{
						title: '合同名称',
						key: 'contractName',
						width: '150',
						sortable: false
					},
					{
						title: '价税合计',
						key: 'totalTaxPrice',
						width: '150',
						sortable: false
					},
					{
						title: '开户行',
						key: 'openingBankName',
						width: '150',
						sortable: false
					},
					{
						title: '物料编码',
						key: 'materialCode',
						width: '150',
						sortable: false
					},
					{
						title: '合同编号',
						key: 'contractNumber',
						width: '250',
						sortable: false
					},
					{
						title: '关联账户',
						key: 'collectingAccountName',
						width: '250',
						sortable: false
					},
					{
						title: '甲方名称',
						key: 'customerName',
						width: '150',
						sortable: false
					},
					{
						title: '物料名称',
						key: 'materialName',
						width: '150',
						sortable: false
					},
					{
						title: '规格',
						key: 'model',
						width: '150',
						sortable: false
					},
					{
						title: '金额',
						key: 'totalAmount',
						width: '150',
						sortable: false
					},
					{
						title: '合同类型	',
						key: 'saleType',
						enum: {
							'1': '普通合同',
							'2': '金额合同',
							'3': '物料分组合同',
							'4': '框架合同'
						},
						width: '150',
						sortable: false
					},

				],
				tcontractTableData: [],
			}
		},
		computed: {
			// 合同录入主单信息
			pageConfig() {
				return this.$t('sellContractEntry')
			},
			// 合同录入主单分组
			groupList() {
				return this.$t('sellContractEntry').groupList
			},
			// 合同录入明细信息
			pageDetailConfig() {
				return this.$t('sellContractEntryDetail')
			},
			// 合同录入明细分组
			groupDetailList() {
				return this.$t('sellContractEntryDetail').groupList
			}
		},
		onReady() {
			// 模块标题
			uni.setNavigationBarTitle({
				title: this.$t('sellContractEntry').basicConfig.title
			});
		},
		onLoad() {
			this.formItemList = this.pageConfig.pageItemConfig
			this.formItemDetailList = this.pageDetailConfig.pageItemConfig
			this.pageFormData = this.$initFormData(this.formItemList)
			this.pageFormDetailData = this.$initFormData(this.formItemDetailList)
			this.initData()
		},
		methods: {
			/**
			 * @explain
			 * 统一处理items的方法
			 * this.$handleItems(data, textKey, valueKey)
			 * 
			 * @explain 
			 * 设置items的方法
			 * this.$setItems(formItemList, key, items)
			 */

			// 通过处理并给对应字段设置下拉内容
			handleAndSetItems(formItemList, data, textKey, valueKey, key) {
				let customerItems = this.$handleItems(data, textKey, valueKey)
				if (customerItems.length > 0) {
					this.$setItems(formItemList, key, customerItems)
				}
			},

			// 表格多选
			selectionChange(rowDataList, indexList) {
				console.log('rowDataList====>', rowDataList);
				console.log('indexList====>', indexList);
			},

			// 数据初始化
			initData() {
				this.getContractData()
				this.getCustomerList()
				this.getSellDepartmentList()
				this.getSalespersonList()
				this.getProjectList()
				this.getKingBankAccountList()
				this.getMaterialList()
			},
			
			getRow(rowData,tableRowData,index){
				this.rowData = rowData
				this.rowIndex = index
			},
			
			// 删除销售合同
			delete(){},
			
			// 编辑销售合同
			edit(){
				// this.pageFormData = {...this.rowData}
				// this.pageFormDetailData = {...this.rowData}
				this.isAdd = true
			},

			// 新增销售合同
			add() {
				this.isAdd = true
			},

			// 获取销售合同数据
			async getContractData() {
				let params = {
					limit: 100,
					page: 1
				}
				let res = await this.$http.postAsync('heart/ContractSale/list', params)
				if (res.data.code === 200) {
					this.tcontractTableData = res.data.data.records
				}
			},

			// 获取物料
			async getMaterialList(val) {
				let params = {
					limit: 100,
					page: 1,
					serachParam: val
				}
				let res = await this.$http.getAsync('heart/Material/queryList', params)
				if (res.data.code === 200) {
					this.materialList = res.data.data.records
					this.handleAndSetItems(this.formItemDetailList, this.materialList, 'materialCode', 'id',
						'materialId')
				}
			},

			// 获取收款账户
			async getKingBankAccountList() {
				let params = {
					limit: 100,
					page: 1
				}
				let res = await this.$http.getAsync('heart/KingBankAccount/list', params)
				if (res.data.total > 0) {
					this.kingBankAccountList = res.data.rows
					this.handleAndSetItems(this.formItemList, this.kingBankAccountList, 'bankName', 'id',
						'collectingAccountId')
				}
			},

			// 获取项目
			async getProjectList() {
				let params = {
					limit: 100,
					page: 1
				}
				let res = await this.$http.getAsync('heart/Project/list', params)
				if (res.data.code === 200) {
					this.projectList = res.data.data.records
					this.handleAndSetItems(this.formItemList, this.projectList, 'projectName', 'id', 'projectId')
				}
			},

			// 获取销售人员
			async getSalespersonList(val) {
				let params = {
					pageSize: 100,
					pageNo: 1,
					serachParam: val
				}
				let res = await this.$http.getAsync('system/user/list', params)
				if (res.data.total > 0) {
					this.salespersonList = res.data.rows
					this.handleAndSetItems(this.formItemList, this.salespersonList, 'nickName', 'userId', 'saleUserId')
				}
			},

			// 获取销售部门
			async getSellDepartmentList() {
				let params = {
					pageSize: 100,
					pageNo: 1,
					level: 2
				}
				let res = await this.$http.getAsync('system/dept/list', params)
				if (res.data.code === 200) {
					// console.log(res)
					this.sellDepartmentList = res.data.data.records
					this.handleAndSetItems(this.formItemList, this.sellDepartmentList, 'deptName', 'deptId',
						'saleDeptId')
				}
			},

			// 获取客户信息
			async getCustomerList() {
				let params = {
					limit: 100,
					page: 1,
					searchParam: ""
				}
				let res = await this.$http.postAsync('heart/Customer/menuCustomerList', params)
				if (res.data.code === 200) {
					this.customerList = res.data.data.records
					this.handleAndSetItems(this.formItemList, this.customerList, 'customerName', 'counterCustomerId',
						'customerName')
				} else {

				}
			},

			// 标签页切换时调用
			onClickTabItem(e) {
				if (this.current !== e.currentIndex) {
					this.current = e.currentIndex
				}
			},

			// 保存按钮点击事件
			async saveFunc(params) {
				console.log(params);
				if (this.tableData.length <= 0) {
					this.$modal.msgError("至少包含一条明细信息")
					return
				}
				let param = {
					contractSaleEntity: {
						...params,
						businessType: '9'
					},
					materialDetailEntities: this.tableData
				}
				let res = await this.$http.postAsync('heart/ContractSale/draft', param)
				if (res.data.code === 200) {
					this.contractId = res.data.data.id
					this.businessType = res.data.data.businessType
					this.$modal.msgSuccess(res.data.msg)
				}
			},

			// 提交按钮点击事件
			async submit() {
				let params = {
					id: this.contractId,
					businessType: this.businessType,
					modelId: ''
				}
				let res = await this.$http.postAsync('heart/ContractSale/submit', params)
				if (res.data.code === 200) {
					this.$modal.msgSuccess(res.data.msg)
				}
			},

			// 明细新增按钮点击事件
			addDetail(params) {
				let dataItem = JSON.parse(JSON.stringify(params))
				this.tableData.push(dataItem)
				this.$refs.formDetail.resetFormData()
			},

			// 远程搜索方法
			remoteSearch(key, items, index, val) {
				switch (key) {
					case 'saleUserId':
						this.getSalespersonList(val)
						break;
				}
			},

			// 明细远程搜索方法
			remoteDetailSearch(key, items, index, val) {
				console.log(key)
				switch (key) {
					case 'materialId':
						this.getMaterialList(val)
						break;
				}
			},

			// 远程搜索下拉框值改变时触发
			selectInputChange(value, key) {
				console.log(this.pageFormData)
			},

			// 明细远程搜索下拉框值改变时触发
			selectInputDetailChange(value, key) {
				switch (key) {
					case 'materialId':
						let activMaterialCode = this.materialList.filter((e) => {
							return e.id === value
						})
						this.pageFormDetailData.materialName = activMaterialCode[0].materialName
						this.pageFormDetailData.materialCode = activMaterialCode[0].materialCode
						this.pageFormDetailData.model = activMaterialCode[0].model
						this.getMaterialList()
						break;
				}
			},

			// 选择器改变时调用
			selectChange(value, key) {
				console.log(value, key);
				// console.log(this.pageFormData)
			},

			// 选择器改变时调用
			selectDetailChange(value, key) {
				console.log(this.pageFormDetailData)
			},
		}
	}
</script>

<style lang="scss" scoped>
	.page-padding {
		padding: 0 0.5rem;
	}

	page {
		padding-bottom: 5rem;
	}

	.btn-box {
		padding: 1rem;
		position: fixed;
		width: 100%;
		min-height: 5rem;
		bottom: 0;
		background-color: #fff;
		display: flex;
		justify-content: space-between;
		flex-wrap: wrap;

		.u-button {
			width: 30%;
		}
	}
</style>